package com.haitaoit.chengquan.pay.alipay;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;

import com.alipay.sdk.app.PayTask;
import com.haitaoit.chengquan.utils.Constant;
import com.lidroid.xutils.util.LogUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class Pay {
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    final Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    break;
                }
                case SDK_CHECK_FLAG: {
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    /**
     * 判断resultStatus 为“9000”则代表支付成功， 判断resultStatus 为非“9000”则代表可能支付失败
     * <p>
     * Pay(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @param context
     * @param subject
     * @param @body
     * @param price
     * @return String
     * @throws
     * @since 1.0.0
     */
    public static void Pay_Pay(final Activity context, String subject,
                               String order_no, String price, final Handler mHandler) {
        String orderInfo = OrderInfo.getOrderInfo(subject, order_no, price);
        String sign = sign(orderInfo);
        LogUtils.e("====sign=======" + sign);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();
        LogUtils.e("====payInfo=======" + payInfo);

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(context);
                // 最新jar包 没有该方法的调用
                //boolean isExist = alipay.checkAccountIfExist();
                String version = alipay.getVersion();

                LogUtils.e("版本号" + version);

                // 调用支付接口
                String result = alipay.pay(payInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    public static String sign(String content) {
        return SignUtils.sign(content, Constant.RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    public static String getSignType() {
        return "sign_type=\"RSA\"";
    }

}